package dao

import (
	"github.com/go-xorm/xorm"

	"im/errcode"
	"im/model"
	"im/service/orm"
)

type SystemConfigs struct {
	db *xorm.Engine
}

func NewSystemConfigs() SystemConfigs {
	return SystemConfigs{db: orm.GetDB()}
}

func (s SystemConfigs) GetConfig(configName string) (string, error) {
	var config model.SystemConfigs
	_, err := s.db.Where("name=?", configName).Get(&config)
	if err != nil {
		return "", errcode.NewError(errcode.DaoFailed, err)
	}
	return config.Detail, nil
}
func (s SystemConfigs) UpdateConfig(configName string, data string) error {
	var m = model.SystemConfigs{
		Detail: data,
	}
	_, err := s.db.Where("name=?", configName).Update(&m)
	if err != nil {
		return errcode.NewError(errcode.DaoFailed, err)
	}
	return nil
}
func (s SystemConfigs) Exists(configName string) (bool, error) {
	var config model.SystemConfigs
	found, err := s.db.Where("name=?", configName).Get(&config)
	if err != nil {
		return found, errcode.NewError(errcode.DaoFailed, err)
	}
	return found, nil
}
func (s SystemConfigs) Insert(configName, config string) error {
	_, err := s.db.InsertOne(&model.SystemConfigs{
		Name:   configName,
		Detail: config,
	})
	if err != nil {
		return errcode.NewError(errcode.DaoFailed, err)
	}
	return nil
}
